package com.zw.cc.redis.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {

    public static final Logger LOGGER = LoggerFactory.getLogger(SerializeUtil.class);

    private SerializeUtil() {
        throw new IllegalStateException("SerializeUtil class");
    }

    // 序列化
    public static byte[] serialize(Object object) {
        try (
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos)
        ) {
            oos.writeObject(object);
            return baos.toByteArray();
        } catch (Exception e) {
            LOGGER.error("SerializeUtil serialize error", e);
        }
        return new byte[]{};
    }

    // 反序列化
    public static Object unSerialize(byte[] bytes) {
        try (
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais)
        ) {
            return ois.readObject();
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return null;
    }

}
